//
//  MZGalleryViewController.m
//  Mehfile Zainab
//
//  Created by Sitara Badourali on 25/02/12.
//  Copyright 2012 Mehfile Zainab. All rights reserved.
//

#import "MZGalleryViewController.h"
#import "UIImage+Scale.h"
#import "CustomImagePicker.h"
#import "MZInfosViewController.h"

@implementation MZGalleryViewController

@synthesize albums;
@synthesize albumsFullPath;

@synthesize imagePicker = _imagePicker;

@synthesize alertView;

@synthesize spinner;

#pragma mark -
#pragma mark View lifecycle

-(IBAction)GoBack:(id)sender
{
	//[self dismissModalViewControllerAnimated:YES];
    [self.navigationController popToRootViewControllerAnimated:YES];
}

/*
- (void)showInfo:(id)sender
{
    NSLog(@"Info button tapped, show modal view");
    MZInfosViewController *mzInfosViewController = [[MZInfosViewController alloc]
                                                    initWithNibName:@"MZInfosViewController" bundle:nil];
    UINavigationController *navController = [[UINavigationController alloc] initWithRootViewController:mzInfosViewController];
    mzInfosViewController.title = @"Informations";
    [mzInfosViewController release];
	navController.modalTransitionStyle = UIModalTransitionStyleFlipHorizontal;
    UIBarButtonItem *barButtonItem = [[UIBarButtonItem alloc]
									  initWithTitle:@"Fermer"
									  style:UIBarButtonItemStyleBordered
									  target:mzInfosViewController
									  action:@selector(GoBack:)];
	mzInfosViewController.navigationItem.leftBarButtonItem = barButtonItem;
    [self.tabBarController presentModalViewController:navController animated:YES];
    [navController release];
    
}
*/

- (void) initGallery {
	//albumsArray = [[NSMutableArray alloc] init];
	albums = [[NSMutableDictionary alloc] init];
    albumsFullPath = [[NSMutableDictionary alloc] init];
	NSError * error;
	NSString * resourcePath = [[NSBundle mainBundle] resourcePath];
	NSLog(@"Resource Path : %@",resourcePath);
	NSArray *temp1 = [[NSFileManager defaultManager] contentsOfDirectoryAtPath:resourcePath error:&error];
	NSLog(@"Content count : %d",[temp1 count]);
	NSString * documentsPath = [resourcePath stringByAppendingPathComponent:@"Gallerie"];
	NSLog(@"Document Path : %@",documentsPath);
	NSArray *tempAlbumsArray = [[NSFileManager defaultManager] contentsOfDirectoryAtPath:documentsPath error:&error];
	NSLog(@"Content count : %d",[tempAlbumsArray count]);
	NSString * albumPath;
	NSArray *tempAlbumsContentArray;
    NSMutableArray *tempAlbumsFullPathContentArray;
	NSInteger i;
	NSInteger j;
	//NSDictionary *tempDict = [[NSDictionary alloc] init];
	//[albumsArray setArray:tempAlbumsArray];
	for (i=0; i<[tempAlbumsArray count]; i++) {
		albumPath = [documentsPath stringByAppendingPathComponent:[tempAlbumsArray objectAtIndex:i]];
        NSLog(@"Album Path : %@",albumPath);
		tempAlbumsContentArray = [[NSFileManager defaultManager] contentsOfDirectoryAtPath:albumPath error:&error];
        tempAlbumsFullPathContentArray = [[NSMutableArray alloc] initWithCapacity:[tempAlbumsContentArray count]];
        for (j=0; j<[tempAlbumsContentArray count]; j++) {
            [tempAlbumsFullPathContentArray addObject:[albumPath stringByAppendingPathComponent:[tempAlbumsContentArray objectAtIndex:j]]];
        }
		NSLog(@"Album Content count : %d",[tempAlbumsContentArray count]);
		[albums setObject:tempAlbumsContentArray forKey:[tempAlbumsArray objectAtIndex:i]];
        [albumsFullPath setObject:tempAlbumsFullPathContentArray forKey:[tempAlbumsArray objectAtIndex:i]];
	}
}

-(void) startLoading:(id)data  {
	
	NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
	
	spinner = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhiteLarge];
	[spinner setCenter:CGPointMake(140, 100)]; 
	
	NSString* messageTitleToUser = @"Mehfile Zainab"; 
	alertView = 
		[[UIAlertView alloc]	initWithTitle:messageTitleToUser 
								message:@"Chargement..." 
								delegate:self 
								cancelButtonTitle:nil
								otherButtonTitles:nil];
	
	[alertView addSubview:spinner];
	[spinner startAnimating];
	[alertView show]; 
	
	[pool drain];
	
}

//-(void) stopLoading:(id)data  {
-(void) stopLoading  {
	//if you programmatically want to close the alert view 
	[alertView dismissWithClickedButtonIndex:0 animated:YES];
	// stop spinner 
	[spinner stopAnimating];
}

- (void)viewDidLoad {
    
	[super viewDidLoad];
	
	//[NSThread detachNewThreadSelector:@selector(startLoading:) toTarget:self withObject:nil];
	
	[self initGallery];
    // Uncomment the following line to display an Edit button in the navigation bar for this view controller.
    // self.navigationItem.rightBarButtonItem = self.editButtonItem;
	
	//[NSThread detachNewThreadSelector:@selector(stopLoading:) toTarget:self withObject:nil];
	
}


/*
- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
}
*/
/*
- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
}
*/
/*
- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
}
*/
/*
- (void)viewDidDisappear:(BOOL)animated {
    [super viewDidDisappear:animated];
}
*/
/*
// Override to allow orientations other than the default portrait orientation.
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
    // Return YES for supported orientations
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}
*/

#pragma mark -
#pragma mark Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    // Return the number of sections.
    //return <#number of sections#>;
	return 1;
}


- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    // Return the number of rows in the section.
    //return <#number of rows in section#>;
	//return [albumsArray count];
	return [[albums allKeys] count];
}

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        //self.title = NSLocalizedString(@"Second", @"Second");
        self.tabBarItem.image = [UIImage imageNamed:@"galery_icon"];
    }
    return self;
}

// Customize the appearance of table view cells.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    static NSString *CellIdentifier = @"Cell";
    
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier] autorelease];
    }
    
    // Configure the cell...
	cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
    //[cell.textLabel setText:[albumsArray objectAtIndex:indexPath.row]];
	NSString *currentAlbum = [[[albums allKeys] sortedArrayUsingSelector:@selector(caseInsensitiveCompare:)] objectAtIndex:indexPath.row]; 
	[cell.textLabel setText:currentAlbum];
	NSString *detailText = [NSString stringWithFormat:@"%d Photo(s)",[[albums objectForKey:currentAlbum] count]];
	[cell.detailTextLabel setText:detailText];
	//NSString *mainImage = [[albums objectForKey:currentAlbum] objectAtIndex:0];
    NSString *mainImageFullPath = [[albumsFullPath objectForKey:currentAlbum] objectAtIndex:0];
    NSLog(@"Main image path : %@",mainImageFullPath);
    /*
    NSBundle* myBundle = [NSBundle mainBundle];
    NSString* mainImage = [myBundle pathForResource:@"_DSC0484" ofType:@"png"];
    */
    //UIImage *image = [UIImage imageNamed:mainImage];
    UIImage *image = [UIImage imageWithContentsOfFile:mainImageFullPath];
	[cell.imageView setImage:[image scaleToSize:CGSizeMake(52.0f,48.0f)]];
	//[image release];
	
    return cell;
}


/*
// Override to support conditional editing of the table view.
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
    // Return NO if you do not want the specified item to be editable.
    return YES;
}
*/


/*
// Override to support editing the table view.
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
    
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        // Delete the row from the data source
        [tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationFade];
    }   
    else if (editingStyle == UITableViewCellEditingStyleInsert) {
        // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
    }   
}
*/


/*
// Override to support rearranging the table view.
- (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)fromIndexPath toIndexPath:(NSIndexPath *)toIndexPath {
}
*/


/*
// Override to support conditional rearranging of the table view.
- (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath {
    // Return NO if you do not want the item to be re-orderable.
    return YES;
}
*/


#pragma mark -
#pragma mark Table view delegate

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
	[tableView deselectRowAtIndexPath:indexPath animated:YES];
    // Navigation logic may go here. Create and push another view controller.
	
	//[NSThread detachNewThreadSelector:@selector(startLoading:) toTarget:self withObject:nil];
	
	_imagePicker = [[CustomImagePicker alloc] init];
    
	NSString *currentAlbum = [[[albums allKeys] sortedArrayUsingSelector:@selector(caseInsensitiveCompare:)] objectAtIndex:indexPath.row]; 
	_imagePicker.title = currentAlbum;
	//NSMutableArray *imagesOfAlbum = [albums objectForKey:currentAlbum];
    NSMutableArray *imagesOfAlbumFullPath = [albumsFullPath objectForKey:currentAlbum];
	//for (NSInteger i=0; i<[imagesOfAlbum count]; i++) {
    for (NSInteger i=0; i<[imagesOfAlbumFullPath count]; i++) {
        //NSString *imageName = [imagesOfAlbum objectAtIndex:i];
        NSString *imageName = [imagesOfAlbumFullPath objectAtIndex:i];
        NSLog(@"Do action on image named : %@",imageName);
        //UIImage *currentImage = [UIImage imageNamed:imageName];
        UIImage *currentImage = [UIImage imageWithContentsOfFile:imageName];
        //if (currentImage) { NSLog(@"Object is not nil"); }
        //else { NSLog(@"WARN : Object is NIL"); }
        [_imagePicker addImage:currentImage];
		//[_imagePicker addImage:[UIImage imageNamed:[imagesOfAlbum objectAtIndex:i]]];
	}
    
    UIBarButtonItem *barButtonItem = [[UIBarButtonItem alloc]
                                      initWithTitle:@"Accueil"
                                      style:UIBarButtonItemStyleBordered
                                      target:self
                                      action:@selector(GoBack:)];
    _imagePicker.navigationItem.rightBarButtonItem = barButtonItem;
    
	[self.navigationController pushViewController:_imagePicker animated:YES];
	
	//[self stopLoading];
	
	/*
	 <#DetailViewController#> *detailViewController = [[<#DetailViewController#> alloc] initWithNibName:@"<#Nib name#>" bundle:nil];
     // ...
     // Pass the selected object to the new view controller.
	 [self.navigationController pushViewController:detailViewController animated:YES];
	 [detailViewController release];
	 */
}


#pragma mark -
#pragma mark Memory management

- (void)didReceiveMemoryWarning {
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
    
    // Relinquish ownership any cached data, images, etc that aren't in use.
}

- (void)viewDidUnload {
    // Relinquish ownership of anything that can be recreated in viewDidLoad or on demand.
    // For example: self.myOutlet = nil;
}


- (void)dealloc {
    [_imagePicker release];
	_imagePicker = nil;
    [super dealloc];
}


@end

